package top.ply.common_unit.token;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtil {

    /**
     * 根据传入的payload、secretKey获取token
     * @param payload 负载信息，可以负载一些类似于用户数据的信息
     * @param secretKey 加密密钥，应该保证这个密钥不被外界知道
     * @param expireTime 多长时间内有效，单位为ms，token在当前时间+expireTime后失效
     * @return 利用传入信息加密后的token
     */
    public static String createToken(Map<String, String> payload, String secretKey, long expireTime) {
        return JWT.create()
                .withPayload(payload)
                .withExpiresAt(new Date(System.currentTimeMillis() + expireTime))
                .sign(Algorithm.HMAC256(secretKey));
    }

    public static boolean isExpire(String token, String secretKey) {
        Date now = new Date();
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secretKey)).build();
        Date expiresAt = verifier.verify(JWT.decode(token)).getExpiresAt();
        if (expiresAt == null) {
            return false;
        }
        return expiresAt.compareTo(now) <= 0;
    }

    public static Map<String, String> getPayload(String token, String secretKey) {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secretKey)).build();
        Map<String, Claim> claims = verifier.verify(token).getClaims();
        if (claims == null) {
            return new HashMap<>();
        }
        Map<String, String> stringPayload = new HashMap<>();
        for (Map.Entry<String, Claim> entry : claims.entrySet()) {
            stringPayload.put(entry.getKey(), entry.getValue().asString());
        }
        return stringPayload;
    }

}
